<template>
  <!-- 机构-站点层级树 -->
  <div class="tree">
    <div class="tree__search pt-4 pb-3 pr-8">
      <a-input
        v-model:value.trim="searchValue"
        :placeholder="props.searchPlaceholder"
        maxLength="100"
        v-filter-special-chars
      >
        <template #prefix>
          <SearchOutlined class="mr-1" />
        </template>
      </a-input>
    </div>
    <a-spin :spinning="loading" class="w-full">
      <div v-if="!loading" class="tree-content">
        <a-tree
          :disabled="disabled"
          v-if="filteredTreeData?.length"
          :defaultExpandAll="true"
          :blockNode="true"
          :tree-data="filteredTreeData"
          @select="handleSelect"
          :autoExpandParent="true"
          class="side-tree"
          :fieldNames="{ children: 'children', title: 'name', key: 'id' }"
          v-model:selectedKeys="selectedKeys"
        >
          <template #title="{ name }">
            <div class="ellipsis-label" :title="name">
              {{ name }}
            </div>
          </template>
        </a-tree>
        <a-empty v-else :image="simpleImage" />
      </div>
    </a-spin>
  </div>
</template>

<script setup lang="ts">
import type { TreeProps } from 'ant-design-vue'
import { onBeforeMount, ref, computed } from 'vue'
import { getUavTree } from '@/api/organization'
import { Empty } from 'ant-design-vue'
import { SearchOutlined } from '@ant-design/icons-vue'
// import { cloneDeep } from 'lodash'

const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE

const emit = defineEmits(['updateCurrent', 'updateRootId', 'updateRootName'])

const props = defineProps({
  searchPlaceholder: {
    type: String,
    default: '请输入'
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

// 顶部搜索框
const searchValue = ref('')
// 根据输入框内容对节点进行过滤,需要过滤机构,输入内容后只显示站点
const filteredTreeData = computed(() => {
  if (searchValue.value) {
    return filterTreeData(treeData.value)
  } else {
    return treeData.value
  }
})

const filterTreeData = (data: TreeProps['treeData']): any => {
  if (!data) return
  return data
    .map((node) => {
      console.log(node, 'node')
      if (node.label.includes(searchValue.value)) {
        if (node.children) {
          return {
            ...node,
            children: filterTreeData(node.children)
          }
        } else {
          return node
        }
      } else {
        if (node.children) {
          const filteredChildren = filterTreeData(node.children)
          if (filteredChildren.length > 0) {
            return {
              ...node,
              children: filteredChildren
            }
          }
        }
      }
      return null
    })
    .filter((node) => node !== null)
}
const treeData = ref<TreeProps['treeData']>([])
const loading = ref(false)
const rootId = ref()
const rootItem = ref()

// 获取组织机构站点树
const getOrgTreeFun = async () => {
  loading.value = true
  getUavTree()
    .then((res) => {
      console.log(res, 'res')
      treeData.value = res
      emit('updateRootId', res[0].id)
      rootId.value = res[0].id
      rootItem.value = res[0]
      emit('updateRootName', res[0].name)
      emit('updateCurrent', res[0])
      loading.value = false
    })
    .catch(() => {
      treeData.value = []
      loading.value = false
    })
}

onBeforeMount(() => {
  getOrgTreeFun()
})

// 选中节点
const currentNode = ref()
const handleSelect = (
  _selectedKeys: any,
  e: { selected: boolean; selectedNodes: any }
) => {
  // eslint-disable-next-line eqeqeq
  if (e.selectedNodes[0] == undefined) {
    currentNode.value = rootItem.value
  } else {
    currentNode.value = e.selectedNodes[0]
  }
  emit('updateCurrent', currentNode.value)
}

const selectedKeys = ref<string[] | number[]>([])

const setSelectedKeys = (value: string[] | number[]) => {
  selectedKeys.value = value
  if (value.length === 0 && treeData.value && treeData.value.length > 0) {
    emit('updateRootId', treeData.value[0].id)
    rootId.value = treeData.value[0].id
    emit('updateRootName', treeData.value[0].name)
    emit('updateCurrent', treeData.value[0])
  }
}

defineExpose({ rootId, setSelectedKeys })
</script>

<style lang="less">
.tree {
  width: 18rem;
  height: 100%;
  border-right: 1px #212c4d solid;

  .ant-input-prefix {
    color: @placeholder-text-color;
  }

  .ant-spin-nested-loading,
  .ant-spin-spinning {
    height: calc(100% - 3.75rem);

    .ant-spin-container {
      height: 100%;

      .tree-content {
        height: 100%;
      }

      .ant-tree {
        overflow-y: auto;
        padding-right: 1.25rem;
        padding-bottom: 1.5rem;
        height: 100%;
      }
    }
  }

  .ant-spin-spinning {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  // .ant-tree {
  //   padding-right: 1.25rem;
  //   padding-bottom: 1.5rem;
  // }
  .ant-tree-title {
    .ellipsis-label {
      overflow: hidden;
      width: 8.5rem;
      text-overflow: ellipsis;
      white-space: nowrap;
      word-break: break-all;
    }

    .ant-tree-indent-unit {
      width: 1rem;
    }
  }
}
</style>
